package org.sandbox2.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.sandbox2.domain.loan.Loan;
import org.sandbox2.domain.loan.LoanFactory;
import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RooWebScaffold(path = "loans", formBackingObject = Loan.class)
@RequestMapping("/loans")
@Controller
public class LoanController {
	
	@RequestMapping(method = RequestMethod.POST)
    public String create(@Valid Loan loan, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            uiModel.addAttribute("loan", loan);
            addDateTimeFormatPatterns(uiModel);
            return "loans/create";
        }
        uiModel.asMap().clear();
        Loan concreteLoan = LoanFactory.createLoan(loan);
        concreteLoan.create(); //facade method 
        return "redirect:/loans/" + encodeUrlPathSegment(concreteLoan.getId().toString(), httpServletRequest);
    }
}
